package com.dunke.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.dunke.core.common.TokenData;
import com.dunke.constants.Constants;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;


@Component
public class TokenUtil {

    /**
     * 生成Token
     * @param data 用户信息
     * @return 生成token值
     */
    public String getToken(TokenData data){
        String token = JWT.create()
                .withAudience(Integer.toString(data.getId()))
                .withAudience(data.getAccount())
                // 签名时间
                .withIssuedAt(new Date())
                // 过期时间
                .withExpiresAt(getEndDate(data.getCreateTime()))
                // 签名
                .sign(Algorithm.HMAC256(Constants.TOKEN_SECRET));
        return token;
    }

    /**
     * 生成token的过期时间
     * @return 过期时间
     */
    private Date getEndDate() {
        return new Date(DateUtils.getCurrentMillis() +
                Constants.TOKEN_EXPIRE_TIME * 1000L);
    }

    /**
     * 生成token的过期时间
     * @return 过期时间
     */
    private Date getEndDate(long time) {
        return new Date(time + Constants.TOKEN_EXPIRE_TIME * 1000L);
    }

    /**
     * 验证Token
     * @param token
     * @return
     * @throws Exception
     */
    public static boolean verifyToken(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        Date news = new Date();
        System.out.println(expiredDate.getTime());
        System.out.println(news.getTime());
        System.out.println(news.before(expiredDate));
        return news.before(expiredDate);
    }

    /**
     * 从token中获取过期时间
     */
    private static Date getExpiredDateFromToken(String token) {
        return JWT.decode(token).getExpiresAt();
    }

    /**
     * 获取指定token中某个属性值
     * @param token Token值
     * @param key 属性
     * @return 属性值
     */
    public static String get(String token, String key){
        List<String> list = JWT.decode(token).getAudience();
        for (String s : list) {
            if (key.equals(s)) {
                return s;
            }
        }
        String userId = list.get(0) ;
        return userId;
    }

    /**
     * 获取request
     * @return
     */
    public static HttpServletRequest getRequest(){
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return requestAttributes == null ? null : requestAttributes.getRequest() ;
    }

    /**
     * 获取token
     */
    public String getToken(HttpServletRequest request)  {
       /* //这里不能塞到token中去，必须要放到session中，或者放到redis中去
        //token放到redis库里面  token表
        // Enumeration<String> headerNames 后期改为存入redis缓存
        //用request里面的token和redis里面的token对比，如果对的上的话就放行，不然就不给过
        Enumeration<String> headerNames = request.getHeaderNames() ;
        while (headerNames.hasMoreElements()){
            String name = headerNames.nextElement() ;
            if(name.equals("token")){
                return request.getHeader("token") ;
            }
        }
        Cookie[] cookies = request.getCookies() ;
        for(Cookie c : cookies){
            if(c.getName().equals("token")){
                return c.getValue() ;
            }
        }*/
        return null;
    }
}
